<template>
  <view>
    <view class=" bg-fff rounded10 m-2 p-3">
      <view class="order-header d-flex d-flex-between d-flex-middle pb-2">
        <text class="font28 color-5C5C5C">订单编号：{{ order.order_no }}</text>
        <text :class="getStatusClass(order.status)" class="font28">
          {{ getStatusText(order.status) }}
        </text>
      </view>

      <view class="order-content d-flex d-flex-bottom">
        <image
            :src="order.course_image "
            class="order-image rounded10"
            mode="aspectFill"
        ></image>
        <view class="ml-3 d-flex-item">
          <view class="font28 text-clamp-two">{{ order.category_name }}</view>
          <view class="font24 color999 mt-1">{{ order.full_category_name }}</view>
          <view class="font24 color999 mt-1">{{ order.created_at }}</view>
        </view>
        <view class="d-flex d-flex-column text-right">
          <view class="font30 font-bold colorf00">
            <text class="font20">¥</text>
            {{ order.amount }}
          </view>
        </view>
      </view>
    </view>

    <view class=" bg-fff rounded10 m-2 p-3">
      <view class="d-flex d-flex-between">
        <view>课程总价：</view>
        <view class="font30 font-bold colorf00">
          <text class="font20">¥</text>
          {{ order.amount }}
        </view>
      </view>

    </view>

    <view class=" bg-fff rounded10 m-2 p-3">
      <view class="d-flex d-flex-between d-flex-middle mb-3" @click="changePay(1)">
        <view class="d-flex d-flex-middle">
          <image class="rounded"
                 src="https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/appUpload/20241228140259-f541dd69-c75e-43ad-a9e9-7aa92250dc3c.png"
                 style="width: 50rpx;height: 50rpx;"></image>
          <text class="ml-1">微信支付</text>
        </view>
        <text :class="payType == 1?'icon-xuanzhong1 colorsuccess':'icon-gouxuan1 color999'" class="iconfont"></text>
      </view>

      <view class="d-flex d-flex-between d-flex-middle" @click="changePay(2)">
        <view class="d-flex d-flex-middle">
          <image class="rounded" src="https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/app/pay_wap.png"
                 style="width: 50rpx;height: 50rpx;"></image>
          <text class="ml-1 mr-1">余额支付</text>
        </view>
        <text :class="payType == 2?'icon-xuanzhong1 colorsuccess':'icon-gouxuan1 color999'" class="iconfont"></text>
      </view>
    </view>

    <view class="position-fixed bottom-0 left-0 right-0 bg px-3">
      <view class="d-flex  pt-3 pb-5 d-flex-around">
        <view v-if="countdown != '已过期'" class="kaitong bg-f8 d-flex d-flex-center d-flex-middle px-3"
              @click="clearOrder(order.order_id)">
          <text class="color999 font32 ">取消付款</text>
        </view>

        <view class="kaitong bg-main d-flex d-flex-center d-flex-middle px-3" @click="createOrder">
          <text class="colorfff font32">
            <text v-if="countdown != '已过期'">剩余：</text>
            {{ countdown }}
          </text>
          <text v-if="countdown != '已过期'" class="colorfff font32 ml-2">继续付款</text>
        </view>

      </view>
    </view>
  </view>
</template>

<script>
import {mapState} from "vuex"
import {payApi} from "@/http/payApi";
import {userApi} from "@/http/userApi";
import pay from '@/mixins/pay.js'

export default {
  mixins: [pay],
  data() {
    return {
      formData: {
        name: ''
      },
      payType: 1,
      order: {},
      countdown: '', // 倒计时显示文本
      countdownTimer: null, // 倒计时定时器
      cashList: []
    }
  },
  onLoad(e) {
    try {
      // 正确获取路由参数
      if (e && e.order) {
        let date = JSON.parse(decodeURIComponent(e.order))
        this.order = date
        console.log(date, '.cate')
      }
    } catch (error) {
      console.error('JSON解析错误:', error)
      // 设置默认值或显示错误提示
      this.order = {}
    }

    // 页面数据加载完成后启动倒计时
    this.$nextTick(() => {
      if (this.order.created_at) {
        this.startCountdown();
      }
    });

  },
  computed: {
    ...mapState({
      loginState: state => state.loginState,
    }),
  },
  methods: {
    // 计算倒计时
    // 计算倒计时
    calculateCountdown() {
      if (!this.order.created_at) return '';

      // 解析创建时间 - 兼容iOS格式
      let createdAt;
      if (typeof this.order.created_at === 'string') {
        // 处理 "yyyy-MM-dd HH:mm:ss" 格式，转换为iOS兼容格式
        if (this.order.created_at.includes('-') && this.order.created_at.includes(':')) {
          // 将 "yyyy-MM-dd HH:mm:ss" 转换为 "yyyy/MM/dd HH:mm:ss"
          const iosCompatibleDate = this.order.created_at.replace(/-/g, '/');
          createdAt = new Date(iosCompatibleDate);
        } else {
          createdAt = new Date(this.order.created_at);
        }
      } else {
        createdAt = new Date(this.order.created_at);
      }

      // 验证日期是否有效
      if (isNaN(createdAt.getTime())) {
        console.error('无效的日期格式:', this.order.created_at);
        return '';
      }

      // 设置过期时间为25分钟（根据需求调整）
      const expireTime = new Date(createdAt.getTime() + 25 * 60 * 1000);
      const now = new Date();

      // 计算剩余时间
      const diff = expireTime.getTime() - now.getTime();

      if (diff <= 0) {
        this.countdown = '已过期';
        this.clearCountdown(); // 清除定时器
        return;
      }

      // 计算小时、分钟、秒
      const hours = Math.floor(diff / (1000 * 60 * 60));
      const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
      const seconds = Math.floor((diff % (1000 * 60)) / 1000);

      // 格式化显示
      this.countdown = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
    },

    // 开始倒计时
    startCountdown() {
      this.calculateCountdown();
      this.countdownTimer = setInterval(() => {
        this.calculateCountdown();
      }, 1000);
    },

    // 清除倒计时
    clearCountdown() {
      if (this.countdownTimer) {
        clearInterval(this.countdownTimer);
        this.countdownTimer = null;
      }
    },
    goUrl(urlPages, data) {
      if (!this.loginState) {
        uni.showToast({
          title: '未登录，请先登录！',
          icon: 'none'
        })
        setTimeout(() => {
          uni.navigateTo({
            url: '/subPages/login/login'
          })
        }, 1500)
      } else {
        uni.navigateTo({
          url: urlPages
        })
      }
    },
    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        1: '等待支付',
        2: '已支付',
        3: '已取消',
        4: '已完成',
        5: '售后中'
      };
      return statusMap[status] || '未知状态';
    },

    // 获取状态样式类
    getStatusClass(status) {
      const classMap = {
        1: 'color-warning', // 等待支付 - 橙色
        2: 'color-success', // 已支付 - 绿色
        3: 'color-gray', // 已完成 - 灰色
        4: 'color-success',    // 已取消 - 绿色
        5: 'color-info'     // 售水中 - 蓝色
      };
      return classMap[status] || '';
    },
    changePay(number) {
      this.payType = number
    },
    getCashList() {
      userApi.cashList().then((res) => {
        this.cashList = res
        console.log('cashList', res)
      }).catch((e) => {

      })
    },
    createOrder() {
      if (this.countdown == '已过期') {
        uni.showToast({
          title: '已过期，请重新下单！',
          icon: 'none'
        })
        return
      }

      let that = this
      uni.showLoading({
        title: '支付中...'
      })
        if (this.order.order_no) {
          that.clientTransferPay(this.order.order_no,'','vipUrl')
        }

    },
    async clearOrder(id) {
      // 添加订单ID参数
        try {
          let res = await payApi.cancelOrder(id);
          // 处理取消成功的逻辑
          uni.showToast({
            title: '订单取消成功',
            icon: 'success'
          });
          setTimeout(() => {
            uni.navigateBack({
              delta: 1
            });
          }, 1500);
        } catch (error) {
          uni.showToast({
            title: '取消失败',
            icon: 'none'
          });
        }
    },
  },
  // 页面销毁前清除定时器
  beforeDestroy() {
    this.clearCountdown();
  }
}
</script>

<style scoped>
.order-image {
  width: 120rpx;
  height: 120rpx;
  background: #e1e1e1;
  flex-shrink: 0;
}

.kaitong {
  height: 80rpx;
  border-radius: 80rpx;
}


</style>
